<?php

include Env::get('EXTEND_PATH').'geohash/src/Geohash.php';
use geohash\Geohash\Geohash;

/**
 * 获取附近的人列表
 * @param $latitude
 * @param $longitude
 * @param $nearbyCustomerList
 * @param string $nearbySortType
 * @return bool
 */
function getNearbyCustomerList($latitude, $longitude, $nearbyCustomerList, $nearbySortType) {

    $sortDistance = [];
    foreach ($nearbyCustomerList as $key=>$val) {

        $distance = getDistance($latitude,
            $longitude, $val['latitude'], $val['longitude']);
        $nearbyCustomerList[$key]['distance'] = $distance;

        //排序列
        $sortDistance[$key] = $distance;
    }

    //距离排序
    array_multisort($sortDistance,
        SORT_ASC, $nearbyCustomerList);

    // 如果距离排序类型为 desc
    if ($nearbySortType == 'desc') {
        array_multisort($sortDistance,
            SORT_DESC, $nearbyCustomerList);
    }

    return $nearbyCustomerList;

}

/**
 * 经纬度转换成Geohash
 * @param $latitude
 * @param $longitude
 * @return string
 */
function geohashEncode($latitude, $longitude) {

    $geohashClass = new Geohash();

    return $geohashClass->encode($latitude, $longitude);

}

/**
 * 计算两个经纬度之间的距离
 * @param $latitude1
 * @param $longitude1
 * @param $latitude2
 * @param $longitude2
 * @return string
 */
function getDistance($latitude1, $longitude1, $latitude2, $longitude2)
{
    $earth_radius = 6371000;   //approximate radius of earth in meters

    $dLat = deg2rad($latitude2 - $latitude1);
    $dLon = deg2rad($longitude2 - $longitude1);
    /*
      Using the
      Haversine formula

      http://en.wikipedia.org/wiki/Haversine_formula
      http://www.codecodex.com/wiki/Calculate_Distance_Between_Two_Points_on_a_Globe
      验证：百度地图  http://developer.baidu.com/map/jsdemo.htm#a6_1
      calculate the distance
    */
    $a = sin($dLat/2) * sin($dLat/2) + cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * sin($dLon/2) * sin($dLon/2);
    $c = 2 * asin(sqrt($a));
    $d = round($earth_radius * $c);

    return $d;
}

/**
 * 格式化距离
 * @param $distance
 * @return string
 */
function formatDistance($distance) {

    $distanceStr = $distance.'米';
    if (strlen($distance) >= 4) {
        // 四舍五入保留两位小数
        $distanceStr = sprintf("%.2f", ($distance/1000)).'公里';
    }

    return $distanceStr;
}